import { UserService } from './../../providers/UserService';
// import { Component } from '@angular/core';
// import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Component, Injector, Input, Output, EventEmitter } from '@angular/core';
import { IonicPage, normalizeURL, NavController, NavParams, ViewController, ToastController, ModalController, LoadingController, ActionSheetController, Platform } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BasePage } from './../basePage';
// import { BaseUI } from '../../common/baseui';
// import { RestProvider } from '../../providers/rest/rest';

//导入四个外部加载进来的组件，具体的安装方法在 09-01 章节
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
import { Crop } from '@ionic-native/crop';

import { PhotoLibrary } from '@ionic-native/photo-library';

import { ImageResizer, ImageResizerOptions } from '@ionic-native/image-resizer';


// import { FileChooser } from '@ionic-native/file-chooser';
declare var cordova: any; //导入第三方的库定义到 TS 项目中
declare var $: any;
/**
 * Generated class for the UploadPicPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-upload-pic',
  templateUrl: 'upload-pic.html',
})
export class UploadPicPage {
  ImageParams: { quality: number; };
  startY: number;
  startX: number;
  userId: string;
  errorMessage: string;
  lastImage: string = null;

  returndata: any;

  data: any

  constructor(
    injector: Injector,
    public navCtrl: NavController,
    public navParams: NavParams,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    // public rest: RestProvider,
    public storage: Storage,
    public actionSheetCtrl: ActionSheetController,
    public camera: Camera,
    private crop: Crop,
    public transfer: Transfer,
    public file: File,
    public filePath: FilePath,
    public platform: Platform,
    public toastCtrl: ToastController,
    public viewCtrl: ViewController,
    public userservice: UserService,
    private photoLibrary: PhotoLibrary,
    private imageResizer: ImageResizer
  ) {
    // super(injector);
  }

  ionViewDidEnter() {
    this.storage.get('UserId').then((val) => {
      if (val != null) {
        this.userId = val;
      }
    });
  }

  presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择图片',
      buttons: [
        {
          text: '从图片库中选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);//调用相册单张上传
            // this.getPhotoLibray();//调用相册，待完善
          }
        },
        {
          text: '使用相机',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }


  //为文件生成一个新的文件名
  createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg"; //拼接文件名
    return newFileName;
  }

  //处理图片的路径为可以上传的路径
  // pathForImage(img) {
  //   if (img === null) {
  //     return '';
  //   } else {
  //     return normalizeURL(cordova.file.dataDirectory + img);
  //   }
  // }
  /**
   * 获取相册
   */
  getPhotoLibray() {
    this.photoLibrary.requestAuthorization().then(() => {
      this.photoLibrary.getLibrary().subscribe({
        next: library => {
          console.log(library)

          // library.forEach(function (libraryItem) {
          //   console.log(libraryItem.id);          // ID of the photo
          //   console.log(libraryItem.photoURL);    // Cross-platform access to photo
          //   console.log(libraryItem.thumbnailURL);// Cross-platform access to thumbnail
          //   console.log(libraryItem.fileName);
          //   console.log(libraryItem.width);
          //   console.log(libraryItem.height);
          //   console.log(libraryItem.creationDate);
          //   console.log(libraryItem.latitude);
          //   console.log(libraryItem.longitude);
          //   console.log(libraryItem.albumIds);    // array of ids of appropriate AlbumItem, only of includeAlbumsData was used
          // });
        },
        error: err => { console.log('could not get photos'); },
        complete: () => {
          console.log('done getting photos'); data => {
            console.log(data)
            console.log(11111)
            console.log(data.getAlbums())
            console.log(22222)
          }
        }
      });
    })
      .catch(err => console.log('permissions weren\'t granted'));
  }
  //将获取到的图片或者相机拍摄到的图片进行一下另存为，用于后期的图片上传使用
  copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
      this.lastImage = newFileName;
      if (this.lastImage != null) {
        this.crop.crop(this.pathForImage(this.lastImage), )
          .then(
          newImage => {
            this.lastImage = '';
            this.lastImage = newImage;
            console.log(this.pathForImage(this.lastImage))
            console.log("66666")
            this.pathForImage(newImage)
            console.log(this.pathForImage(newImage))
            //  this.lastImage = newImage;
            console.log(this.lastImage)
            console.log(this.pathForImage(this.lastImage))
            console.log("66666")
          },
          error => console.error('Error cropping image', error)
          );
      }
    }, error => {
      // super.showToast(this.toastCtrl, "存储图片到本地图库出现错误。");
    });
  }



  takePicture(sourceType) {
    //定义相机的一些参数
    var options = {
      quality: 100, //图片的质量
      sourceType: sourceType,
      saveToPhotoAlbum: false, //是否保存拍摄的照片到相册中去
      correctOrientation: true //是否纠正拍摄的照片的方向
    };

    //获取图片的方法
    this.camera.getPicture(options).then((imagePath) => {
      //特别处理 android 平台的文件路径问题
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath) //获取 android 平台下的真实路径
          .then(filePath => {
            //获取正确的路径
            let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
            //获取正确的文  件名
            let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
            this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
          });
        this.toastCtrl.create({
          // message: '安卓平台' + correctPath + '+ && +' + currentName,
          message: '安卓平台' + this.pathForImage(this.lastImage),
          duration: 3000,
          position: 'top',
        }).present();

      }
      else {
        //获取正确的路径
        var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
        //获取正确的文件名
        var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());

        /**
         * 
         */
        this.toastCtrl.create({
          message: 'IOS平台' + this.pathForImage(this.lastImage),
          duration: 3000,
          position: 'top',
        }).present();
      }

      console.log(this.lastImage)
      console.log("lastImage")
      console.log(this.pathForImage(this.lastImage))
      this.ImageParams = { quality: 75 }

    }, (err) => {
      // super.showToast(this.toastCtrl, "选择图片出现错误，请在 App 中操作或检查相关权限。");
      /**
         * 
         */
      this.toastCtrl.create({
        message: err,
        duration: 3000,
        position: 'middle',
      }).present();
    });
  }

  // <<<<<<< .mine
  // ||||||| .r424
  //处理图片的路径为可以上传的路径
  // public pathForImage(img) {
  //   if (img === null) {
  //     return '';
  //   } else {
  //     return normalizeURL(cordova.file.dataDirectory + img);
  //   }
  // }
  // =======
  //处理图片的路径为可以上传的路径
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      this.data = normalizeURL(cordova.file.dataDirectory + img);
      return normalizeURL(cordova.file.dataDirectory + img);
    }
  }
  // >>>>>>> .r432




  async uploadImage() {
    // var url = 'http://app.mengfeisi.com.cn/Admin/Api/uploadImg';
    var url = 'http://192.168.1.99:7777/admin/api/uploadCommon';
    var targetPath = this.lastImage;
    var filename = this.userId + ".jpg"; //定义上传后的文件名

    //fileTransfer 上传的参数
    var option = {
      fileKey: "file",
      fileName: filename,
      httpMethod: 'post',
      chunkedMode: true,
      mimeType: "multipart/form-data",
      params: { img: targetPath }
    };

    const fileTransfer: TransferObject = this.transfer.create();

    // var loading = super.showLoading(this.loadingCtrl, "上传中...");
    var loading = this.loadingCtrl.create({
      content: "上传中...",
      //duration: 3000,
    })
    loading.present();

    // let res=await this.userservice.uploadImgAPI(targetPath);
    // console.log(res)
    //开始正式地上传
    fileTransfer.upload(targetPath, url, option).then(data => {
      console.log(data);
      console.log(777778);
      
      this.returndata = data.response;
      let returnImg = this.returndata.toString();
      var imgobj = eval('(' + returnImg + ')');
      // var imgobj = eval('(' + returnImg + ')');
      // var dataTo = eval('(' + this.data + ')');
      console.log(imgobj)
      // console.log(dataTo)
      loading.dismiss();
      // super.showToast(this.toastCtrl, "图片上传成功。");
      this.toastCtrl.create({
        message: '图片上传成功。',
        duration: 3000,
        position: 'top',
      }).present();
      //在用户看清弹窗提示后进行页面的关闭
      setTimeout(() => {
        this.viewCtrl.dismiss(imgobj);
      }, 2000);
    }, err => {
      loading.dismiss();
      // super.showToast(this.toastCtrl, "图片上传发生错误，请重试。");
      this.toastCtrl.create({
        message: '图片上传发生错误，请重试。',
        duration: 3000,
        position: 'bottom',
      }).present();
    });
  }


  /**返回上一级目录 */
  dismissCLI() {
    console.log(this.returndata);
    console.log('2222222');
    this.viewCtrl.dismiss();
  }

}
